package com.wbc.smartHome.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wbc.smartHome.dao.CommunityActivitiesDao;
import com.wbc.smartHome.dao.CommunityActivitiesLabelDao;
import com.wbc.smartHome.model.CommunityActivities;
import com.wbc.smartHome.model.CommunityActivitiesLabel;
import com.wbc.smartHome.model.Result;
import com.wbc.smartHome.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class CommunityActivitiesService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;


    @Autowired
    private RedisTemplate redisTemplate;

    private String key = "communityactivities";
    @Autowired
    private CommunityActivitiesDao communityActivitiesDao;
    @Autowired
    private CommunityActivitiesLabelDao communityActivitiesLabelDao;

    public List<CommunityActivities> getCommunityActivitiesList() {
        /*ListOperations listOps  = redisTemplate.opsForList();
        List<CommunityActivities> hotSpotList = listOps.range(key, 0, -1);*/
        List<CommunityActivities> communityActivitiesList = communityActivitiesDao.getCommunityActivitiesList();
        return communityActivitiesList;
    }


    public void setCommunityActivities(CommunityActivities communityActivities,String adminToken) {
      /*ListOperations listOps  = redisTemplate.opsForList();
        listOps.rightPush(key, communityActivities);*/
        int adminId = JWTUtil.getAdmin(adminToken).getId();
        communityActivities.setAdminId(adminId);
        communityActivitiesDao.setCommunityActivities(communityActivities);
        int communityActivitiesId = communityActivitiesDao.getCommunityActivitiesIdByTitle(communityActivities.getTitle());
        List<CommunityActivitiesLabel> communityActivitiesLabelList = communityActivities.getCommunityActivitiesLabelList();
        for(CommunityActivitiesLabel communityActivitiesLabel:communityActivitiesLabelList){
            communityActivitiesDao.setLabelRelationship(communityActivitiesLabel.getId(),communityActivitiesId,adminId);
        }
    }

    /*通过标签id查询活动列表*/
    public List<CommunityActivities> getCommunityActivitiesLabelNameByLabelId(Integer labelId) {
        List<CommunityActivities> communityActivitiesList = communityActivitiesDao.getCommunityActivitiesLabelNameByLabelId(labelId);
        return communityActivitiesList;
    }

    /*按照id查询活动并将标签封装进属性*/
    public CommunityActivities getCommunityActivitiesById(Integer id) {
        CommunityActivities communityActivities = communityActivitiesDao.getCommunityActivitiesById(id);
        List<CommunityActivitiesLabel> list = communityActivitiesLabelDao.getCommunityActivitiesLabelByActivitiesId(id);
        if (list==null){
            return communityActivities;
        }
        communityActivities.setCommunityActivitiesLabelList(list);
        return communityActivities;
    }

    /*随机推荐活动*/
    public List<CommunityActivities> getRecommendCommunityActivities() {
        List<CommunityActivities> communityActivitiesList = communityActivitiesDao.getRecommendCommunityActivities();
        // 生成五个不重复的随机索引
        Set<Integer> indexSet = new HashSet<>();
        Random random = new Random();
        while (indexSet.size() < 5 && indexSet.size() < communityActivitiesList.size()) {
            indexSet.add(random.nextInt(communityActivitiesList.size()));
        }
        // 将随机索引中对应的元素存入新的ArrayList
        ArrayList<CommunityActivities> recommendList = new ArrayList<>();
        for (Integer index : indexSet) {
            recommendList.add(communityActivitiesList.get(index));
        }
        return recommendList;
    }

    public PageInfo<CommunityActivities> communityActivitiesList(CommunityActivities communityActivities) {
        PageHelper.startPage(communityActivities.getPageNo(), communityActivities.getPageSize());
        List<CommunityActivities> communityActivitiesList = communityActivitiesDao.communityActivitiesList(communityActivities);
        PageInfo<CommunityActivities> pageInfo = new PageInfo<>(communityActivitiesList);
        return pageInfo;
    }

    public Result uploadImg(CommonsMultipartFile commonsMultipartFile) throws IOException {
        //为了避免上传的文件重名,重新生成一个文件名
        String newFileName = new Date().getTime()+commonsMultipartFile.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);
        //长传文件
        ossClient.putObject(bucketName, newFileName, commonsMultipartFile.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newFileName;
        //newsDao.savePhoto(url);
        return new Result(200,"操作成功",url);
    }

    public void deleteImg(String url) {
        System.out.println(url);
        String objectName = url.substring(48,url.length()-1);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    public void delete(int id) {
        communityActivitiesDao.delete(id);
    }

    public List<CommunityActivitiesLabel> getCommunityActivitiesLabelList() {
        return  communityActivitiesDao.getCommunityActivitiesLabelList();
    }

    public void updateCommunityActivities(CommunityActivities communityActivities, String adminToken) {
        int adminId = JWTUtil.getAdmin(adminToken).getId();
        communityActivities.setAdminId(adminId);
        communityActivitiesDao.updateCommunityActivities(communityActivities);
        communityActivitiesDao.deleteLabelByActivitiesId(communityActivities.getId());
        List<CommunityActivitiesLabel> list = communityActivities.getCommunityActivitiesLabelList();
        for (CommunityActivitiesLabel communityActivitiesLabel : list) {
            communityActivitiesDao.addLabelByActivitiesId(communityActivitiesLabel.getId(),communityActivities.getId(),adminId);
        }
    }
}
